import Emitter from './emitter';

class Loader extends Emitter {
    constructor(url) {
        super();
        this._url = url;
    }

    get url() {
        return this._url;
    }

    _load() {
        return new Promise(resolve => {
            this.emit('start');
            let xhr = new XMLHttpRequest();
            xhr.open('GET', this.url);
            xhr.responseType = 'blob';
            xhr.addEventListener('readystatechange', () => {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    this.emit('loaded');
                    resolve(xhr.response);
                }
            });
            xhr.addEventListener('progress', ({ loaded, total }) => this.emit('progress', { loaded, total }));
            xhr.send();
        });
    }

    _parse(blob) {
        return unzip(blob, { useWorkers: true }).then(({ entries }) => new Source(entries));
    }

    load() {
        return this._load().then(blob => this._parse(blob));
    }
}

export default Loader;